import time
from datetime import datetime
from urllib import request
import json

from api.api_project import public_data


def __get_ulr(project, channel_code, period=""):
    """
        根据通信渠道号、项目和查询的周期生成查询的网址

    """
    url_base = r"http://once/once/document_search?"
    para_time = f"t={str(int(time.time() * 1000))}"
    para1 = f"currentAppCode=app_ae_document&searchParams=%257B%2522searchTerm%2522%3A%2522*{project}*{channel_code}*%2522%2C%2522c_project_code%2522%3A%2522{project}%2522%257D"
    end_str = f"&clearFacet=true&indexRange=&searchVersion=&searchMode=AND&validDateRange={period}&sortType=r_creation_date%7Cdesc&pageSize=1000&pageIndex="
    url = url_base + para_time + para1 + end_str
    return url


def __get_once_json(url, index_page):
    """根据地址和页码获取查询的数据"""
    if public_data.Token:
        headers = ('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Trident/7.0; rv:11.0) like Gecko')
        url_str = url + str(index_page) + "&" + public_data.Token

        opener = request.build_opener()
        opener.addheaders = [headers]

        body = "html"
        times = 0
        while "html" in body and times<5:
            req = opener.open(url_str)
            body = req.read().decode('utf-8')
            times +=1
            
        return json.loads(body)
    print("获取登录验证不成功！")


def get_once_json(project, channel_code, period="", index_page=1):
    url = __get_ulr(project, channel_code, period)
    return __get_once_json(url, index_page)
